package com.sayyi.demo.test.business.service.impl;

import com.sayyi.demo.test.business.domain.UserInfo;
import com.sayyi.demo.test.business.mapper.UserInfoMapper;
import com.sayyi.demo.test.business.service.UserInfoService;
import com.sayyi.demo.test.common.GlobalException;
import com.sayyi.demo.test.common.ResultStatus;
import org.springframework.stereotype.Service;

/**
 * @author xuchuang
 * date 2021/12/24 4:52 PM
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private UserInfoMapper userInfoMapper;

    public UserInfoServiceImpl(UserInfoMapper userInfoMapper) {
        this.userInfoMapper = userInfoMapper;
    }

    @Override
    public long save(UserInfo userInfo) {
        userInfoMapper.save(userInfo);
        return userInfo.getId();
    }

    @Override
    public UserInfo getById(long id) {
        return userInfoMapper.getById(id);
    }

    @Override
    public int updateById(UserInfo userInfo) {
        return userInfoMapper.updateById(userInfo);
    }

    @Override
    public int deleteById(long id) {
        if (isAdmin(id)) {
            throw new GlobalException(ResultStatus.ADMIN_CANT_REMOVE);
        }
        return userInfoMapper.deleteById(id);
    }

    @Override
    public int deleteWithCheck(long id) {
        UserInfo userInfo = this.getById(id);
        if (userInfo == null) {
            return 0;
        }
        return this.deleteById(id);
    }

    /**
     * 是否为admin id
     * @param id    用户id
     * @return  是否为admin id
     */
    private boolean isAdmin(long id) {
        return id == 1;
    }
}
